/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.members;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.members.IntegralRuleBranchService;
import com.qinyeit.serviceapp.service.members.IntegralRuleService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: IntegralRulesController <br/>
 * Function: integralRule [积分规则] <br/>
 * date: 2018-12-04 10:49:12 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/members/integralRules")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_integralRule:read",name ="积分规则",deleteAble = false)
public class IntegralRulesController extends BaseManagementController{

	@Autowired
	private IntegralRuleService integralRuleService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private IntegralRuleBranchService integralRuleBranchService;
	@Autowired
    private BranchService branchService;

	private final String [] keys = {"id","name","integral","amount","startTime","endTime","state","branchs","immediatelyExchange"};

//    @RequiresPermissions("management_integralRule:show")
    @PermissionInfo(code = "management_integralRule:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<IntegralRule> integralRulePage = integralRuleService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(integralRulePage.getContent())){
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            Branch branch = null;
            String branchs = "";
            int count = 0;
            List<IntegralRuleBranch> branchList = null;
            for (IntegralRule rule : integralRulePage.getContent()) {
                branchs = "";
                count =0;
                searchable.addSearchParam("integralRuleId_eq",rule.getId());
                branchList = integralRuleBranchService.findWithSort(searchable);
                if(CollectionUtils.isNotEmpty(branchList)){
                    for (IntegralRuleBranch integralRuleBranch : branchList) {
                        branch = branchService.findById(integralRuleBranch.getBranchId());
                        if (count<3){
                            branchs+=branch.getName()+",";
                        }else {
                            break;
                        }
                        count++;
                    }
                }
                rule.setBranchs(StringUtils.isBlank(branchs)?"":branchs.substring(0,branchs.length()-1));
            }
        }
        return ok("查询成功", JSONUtils.include(integralRulePage,new Class[]{State.class}, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("integralRule",JSONUtils.include(new IntegralRule(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_integralRule:create")
    @PermissionInfo(code = "management_integralRule:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid IntegralRule integralRule, BindingResult bindingResult){
        if(integralRuleService.exists(SearchableUtils.buildExists(null, "name", integralRule.getName()))){
             throw new BusinessRunTimeException("名称已经存在",10001);
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        integralRule.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        integralRule.setUuid(LocalUtils.getUUID());
        integralRule.setUpdateTimestamp(DateUtils.current());
        integralRuleService.save(integralRule);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute IntegralRule integralRule){
        return ok("查询成功", JSONUtils.include(integralRule, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute IntegralRule integralRule){
        QyMap map=QyMap.NEW();
        map.setv("integralRule",JSONUtils.include(integralRule, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_integralRule:update")
    @PermissionInfo(code = "management_integralRule:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid IntegralRule integralRule,BindingResult bindingResult){
        if(integralRuleService.exists(SearchableUtils.buildExists(integralRule.getId(), "name", integralRule.getName()))){
            throw new BusinessRunTimeException("名称已经存在",10001);
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        integralRule.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        integralRule.setUpdateTimestamp(DateUtils.current());
        integralRuleService.update(integralRule);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_integralRule:destory")
    @PermissionInfo(code = "management_integralRule:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        integralRuleService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 分配门店 初始化
     * @param id
     * @return
     */
    @GetMapping("/allocationBranch")
    public ResponseResult<String> allocationBranch(Long id){
        QyMap map = QyMap.NEW();
        //区域门店
//        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
        map.setv("districts",getDistricts());
        if (id!=null){
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("integralRuleId_eq",id);
            List<IntegralRuleBranch> branchList = integralRuleBranchService.findWithSort(searchable);
            Branch branchEn = null;
            if(CollectionUtils.isNotEmpty(branchList)){
                for (IntegralRuleBranch branch : branchList) {
                    branchEn = branchService.findById(branch.getBranchId());
                    branch.setLabel(branchEn.getName());
                }
            }
            map.setv("branchList",JSONUtils.include(branchList,"branchId","districtId","label"));
        }
        return ok("查询成功", map);
    }


    /**
     * 分配门店 保存 (可批量分配机构)
     * @param data
     * @return
     */
    @RequiresPermissions("management_integralRule:allocationBranch")
    @PermissionInfo(code = "management_integralRule:allocationBranch",name ="分配门店",deleteAble = false)
    @PostMapping("/allocationBranch")
    public ResponseResult<String> allocationBranchSave(@RequestBody JSONObject data){
        integralRuleService.allocationBranchSave(data);
        return ok("保存成功");
    }


    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_integralRule:updateState")
    @PermissionInfo(code = "management_integralRule:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        if(id==null){
            throw new BusinessRunTimeException("请选择付款方式",1001);
        }
        IntegralRule rule = integralRuleService.findById(id);
        if(rule.getState()==State.NORMAL){
            rule.setState(State.DISABLED);
        }else {
            rule.setState(State.NORMAL);
        }
        integralRuleService.update(rule);
        return ok("操作成功", null);
    }

    /**
     * 查看所有门店
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_dishesMenu:updateState")
    @PermissionInfo(code = "management_dishesMenu:updateState",name ="查看门店",deleteAble = false)
    @GetMapping("/showAllBranchs")
    public ResponseResult<String> showAllBranchs(Long id){
        IntegralRule integralRule = integralRuleService.findById(id);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("integralRuleId_eq",integralRule.getId());
        List<IntegralRuleBranch> branchList = integralRuleBranchService.findWithSort(searchable);
        Branch branch = null;
        if(CollectionUtils.isNotEmpty(branchList)){
            for (IntegralRuleBranch integralRuleBranch : branchList) {
                branch = branchService.findById(integralRuleBranch.getBranchId());
                integralRuleBranch.setLabel(branch.getName());
            }
        }
        return ok("操作成功", JSONUtils.include(branchList,"id","branchId","districtId","label"));
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            IntegralRule integralRule = integralRuleService.findById(Long.valueOf(id));
            model.addAttribute(integralRule);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        qyMap.setv("states", State.values());
    }

}